// pages/home/history/history.js
import * as echarts from '../../component/ec-canvas/echarts';
const call = require('../../utils/request.js')
const util = require('../../utils/util.js')
let chart = null; //散点图
let chartPie = null; //饼状图
let chartTree1 = null,chartTree2 = null; //树型图
let comp = null,compPie=null,compTree1=null,compTree2=null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentData: 1, //日志0 统计1
    statisticsType: 0, //本周0 本月1
    DayStatistics:{}, //日统计内容
    timeLog:'', //日志选择日期
    time:'', //日统计日期
    pageSize: 10, //日志 每页条数
    pageIndex: 1, //日志 当前页数
    mealsType:{
      1:'早餐前',
      2:'早餐后',
      3:'午餐前',
      4:'午餐后',
      5:'晚餐前',
      6:'晚餐后',
      7:'睡前',
    },
    stateType:{
      1:'正常',
      2:'低血糖',
      3:'高血糖'
    },
    color:{
      '正常':'green',
      '偏低':'blue',
      '偏高':'red'
    },
    ec: {
      // onInit: initChart
      lazyLoad: true
    },
    pie:{
      // onInit:initPie
      lazyLoad: true
    },
    bar1:{
      // onInit: initBar1
      lazyLoad: true
    },
    bar2:{
      // onInit: initBar2
      lazyLoad: true
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取所有echart对象
    comp = this.selectComponent('#mychart-dom-bar');
    compPie = this.selectComponent('#mychart-dom-pie');
    compTree1 = this.selectComponent('#mychart-dom-bar1');
    compTree2 = this.selectComponent('#mychart-dom-bar2');

    //获取日期段
    let date = new Date();
    let year = date.getFullYear();
    let time = util.formatTime(new Date(),'date');
    //获取本周本月日期
    let objDate = util.timeSlot(new Date())

    this.setData({
      startTime: (year-10)+'-01-01',
      endTime:(year+10)+'-12-31',
      time: time,
      week: [objDate.week[0],objDate.week[1]],
      month:[objDate.month[0],objDate.month[1]],
    })

    //获取日志
    // this.getLogList();

    initChart(); initPie(); initBar1(); initBar2();
    //日统计/周月统计
    this.getDayStatistics();
    this.getMonthStatistics();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.currentData == 0){
      if(this.data.logList[parseInt(this.data.pageIndex)-1].length == 0)  return; //是否最后的查询还有数据
      this.setData({
        pageIndex: (this.data.pageIndex+1)
      })
      this.getLogList()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  
  /**
   * 选择数据类型 日志/统计
   */
  chooseType(e){
    let that = this;
    const current = e.currentTarget.dataset.current
    const isFirst = this.data.first_initTable||0;
    if (that.data.currentData === current){
      return false;
    }else{
      let data = {currentData: current}
      if(current == 0){data = Object.assign(data,{first_initTable:1})}
      that.setData(data)
      if(current==0 && isFirst==0){
        this.getLogList()
      }
      // if(current == 1 && isFirst==0){
      //   initChart(); initPie(); initBar1(); initBar2();
      //   //日统计/周月统计
      //   this.getDayStatistics();
      //   this.getMonthStatistics();
      // }else if(current == 0){
      //   this.getLogList();
      // }
    }
  },

  /**
   * 日志 -- 获取日志列表 
   */
  getLogList(){
    const page = this.data.pageIndex;
    let data = {
      size: this.data.pageSize,
      page: page,
      time: this.data.timeLog
    }
    wx.showLoading({
      title: '正在加载日志信息',
      mask:true
    })
    call.post('/api/index/log_list',data).then(res=>{
      console.log("获取日志列表",res)
      wx.hideLoading();
      if(Object.keys(res.data.data.data).length == 0 && page == 1){
        // wx.showToast({
        //   title: '查无日志信息',
        //   icon:'none'
        // })
      }else{
        if(page == 1){
          this.setData({
            [`logList`]: [res.data.data.data]
          })
        }else{
          this.setData({
            [`logList[${page-1}]`]: res.data.data.data
          })
        }
      }
      
    })
  },

  /** 
   * 统计 -- 时间双向绑定
   */
  bindChange(e){
    const name = e.currentTarget.dataset.name;
    this.setData({
      [`${name}`] : e.detail.value
    })
    if(name == 'time'){
      this.getDayStatistics();
    } else{
      this.setData({
        pageIndex:1,
        logList:{}
      })
      this.getLogList();
    }
  },

  /** 
   * 统计 -- 日统计
   */
  getDayStatistics(){
    wx.showLoading({
      title: '正在加载',
      mask:true
    })
    const nowtime = this.data.time;
    let time1 = util.formatTime(new Date(new Date(nowtime).getTime()+24*60*60*1000),"date");
    call.post('/api/index/day_log',{
      time: nowtime
    }).then(res=>{
      console.log("日统计",res)
      const DayStatistics = res.data.data;
      // this.setData({
      //   DayStatistics: DayStatistics
      // })
      //刷新当前散点图  arr胰岛素 arr1正常 arr2低血糖 arr3高血糖 arr4默认，
      let arr = [],arr1 = [[],[],[],[]],lineArr=[]; 
      let heightPoint = 0;
      let downPoint= 0;
      let normalPoint = 0;
      let allPoint = 0; //总次数
      for(let i of DayStatistics.insulin){
        let time = i.maked_at;
        arr.push([time,0,i.insulin_name_cn,i.insulin_dosage])
      }
      for(let i of DayStatistics.glucose){
        let time = i.test_at;
        lineArr.push([time,parseFloat(i.glu)]);
        arr1[i.state].push([time,parseFloat(i.glu)]);
        if(i.state == 1) normalPoint+=1;
        else if(i.state == 2) downPoint+=1;
        else if(i.state == 3) heightPoint+=1;
        allPoint+=1;
      }
      this.setData({
        normalPoint,downPoint,heightPoint,allPoint
      })
      // arr1 = arr1.length == 0?[0,0]:arr;
      console.log("散点图数据",arr,arr1)
      if(chart){
        chart.setOption({
          series: [{
            data:lineArr
          },{
            data: arr
          },{
            data: arr1[1]
          },{
            data: arr1[2]
          },{
            data: arr1[3]
          },{
            data:[[`${nowtime} 00:00:00`,0],[`${time1} 00:00:00`,0]]
          }]
        })
      }
      wx.hideLoading();
    })
  },

  /** 
   * 统计 -- 周/月统计
   */
  getMonthStatistics(){
    wx.showLoading({
      title: '正在加载数据',
      mask:true
    })
    call.post('/api/index/month_log',{
      state: (parseInt(this.data.statisticsType)+1)
    }).then(res=>{
      console.log("周/月统计",res)
      this.setData({
        MonthStatistics:res.data.data
      })
      //饼状图赋值
      if(chartPie){
        chartPie.setOption({
          graphic:{
            style:{
                text:res.data.data.total,
            }
          },
          series:[{
            data: [{
              value: res.data.data.down,
              point: parseInt(res.data.data.downPoint)*100,
              name: '低血糖'
            }, {
              value: res.data.data.normal,
              point: parseInt(res.data.data.normalPoint)*100,
              name: '正常'
            },{
              value: res.data.data.height,
              point: parseInt(res.data.data.heightPoint)*100,
              name: '高血糖'
            }]
          }]
        })
      }
      
      //属性图赋值
      if(chartTree1){
        chartTree1.setOption({
          series: [{
            data: [res.data.data.maxGlu,res.data.data.minGlu]
          }]
        })
      }
      if(chartTree2){
        chartTree2.setOption({
          series: [{
            type: 'bar',
            barWidth: 20,
            data: [res.data.data.beforeMeal,res.data.data.afterMeal,res.data.data.beforeBed]
          }]
        })
      }
      wx.hideLoading();
    })
  },

  /**
   * 统计 -- 切换本月 本周 刷新饼图数据
   */
  changePie(e){
    let that = this;
    const type = e.currentTarget.dataset.type;
    if (that.data.statisticsType === type){
      return false;
    }else{
      that.setData({
        statisticsType: type
      })
      this.getMonthStatistics();
    }
  },

})

/**
 * 获取dpr
 */
function getPixelRatio(){
  let pixelRatio = 0
  wx.getSystemInfo({
    success: function (res) {
      pixelRatio = res.pixelRatio
    },
    fail: function () {
      pixelRatio = 0
    }
  })
  return pixelRatio
}
/**
 * 统计 -- 散点图
 */
function initChart(canvas, width, height, dpr) {
  dpr = getPixelRatio();
  comp.init((canvas, width, height) =>{
    chart = echarts.init(canvas, null, {
      width: width,
      height: height,
      devicePixelRatio: dpr // new
    });
    canvas.setChart(chart);

    var axisCommonX = {
      type: 'time',
      splitLine:{
        show:false
      },
      // interval:200,
      // 坐标轴字体
      axisLabel: {
        textStyle: {
          color: '#333333'
        },
        formatter: function(value, index){
          var t_date = new Date(value);
          let hour = t_date.getHours()<10?'0'+t_date.getHours():t_date.getHours();
          let min = t_date.getMinutes()<10?t_date.getMinutes()+'0':t_date.getMinutes();
          return [hour, min].join(':');
        },
      },
      // 超出的部分
      axisTick: {
        inside:true,
        lineStyle: {
          color: '#00726D'
        }
      },
      // 最外层坐标轴
      axisLine: {
        lineStyle: {
          color: '#00726D'
        }
      },
      // 网格线
      splitLine: {
        show:false
      },
    },
    axisCommonY = {
      type:'value',
      max:40,
      min:0,
      // 坐标轴字体
      axisLabel: {
        textStyle: {
          color: '#C8C8C8'
        }
      },
      // 超出的部分
      axisTick: {
        show:false,
        lineStyle: {
          color: '#fff'
        }
      },
      // 最外层坐标轴
      axisLine: {
        show:false,
        lineStyle: {
          color: '#C8C8C8'
        }
      },
      // 网格线
      splitLine: {
        lineStyle: {
          color: '#C8C8C8',
          type: 'dotted'
        }
      },
    };

    var option = {
      grid:{
        top: 30,
        bottom:30,
        right: 30,
        left: 50
      },
      color: ["","#0B8887","#0B8887","#3399FF","#FF5755","#FF5755"],
      backgroundColor: '#FFF',
      xAxis: axisCommonX,
      yAxis: axisCommonY,
      // dataZoom: [{
      //   type: 'inside', //inside内置  slider有滚动条
      //   show: false,
      //   xAxisIndex: [0], //是否按比例伸缩数据
      //   left: '9%',
      //   bottom: -5,
      //   start: 0,
      //   end: 50 //初始化滚动条
      // }],
      // 数据图形显示
      series: [{
        type:'line',
        symbol: 'circle',
        smooth:true,
        hoverAnimation: false,
        name: 'line',
        data: [],
        lineStyle: { normal: { color: '#00726D', width: 1 ,type:'dashed'} },
      },{
        type: 'scatter',
        symbol:`path://M-15553.967-2220.9a.5.5,0,0,1-.133-.695l1.048-1.554-.634-.433c-.164-.113.487-.847.683-1.116s.3-2.194.484-2.615,6.183-9.439,6.581-9.79a2.38,2.38,0,0,1,2.74-.109,2.12,2.12,0,0,1,.887,2.479c-.2.371-5.895,9.431-6.371,9.872s-1.964,1.3-2.275,1.663-.57,1.1-.73.984l-.539-.37-1.046,1.553a.5.5,0,0,1-.415.219A.5.5,0,0,1-15553.967-2220.9Z`,
        symbolSize:20,
        id:'insulin',
        name: '胰岛素',
        data: []
      },{
        id:'xt1',
        name: '正常',
        type: 'scatter',
        data: []
      },{
        id:'xt2',
        name: '低血糖',
        type: 'scatter',
        data: []
      },{
        id:'xt3',
        name: '高血糖',
        type: 'scatter',
        data: []
      },{
        name:'.anchor',
        type:'line', 
        showSymbol:false, 
        data:[],
        itemStyle:{normal:{opacity:0}},
        lineStyle:{normal:{opacity:0}}
      }],
      tooltip: {  
        /*返回需要的信息*/  
        formatter: function(param) {  
            var value = param.value;  
            let time = value[0].split(' ')[1];
            time = time.substring(0,time.length - 3);
            console.log(param)
            if(param.seriesId == 'insulin'){
              return `${time}\n注射${value[2]}${value[3]}U`;  
            }else{
              return `${time}\n血糖：${value[1]}mmol/L`;  
            }
        }  
      },
      animationDelay: function (idx) {
        return idx * 50;
      },
      animationEasing: 'elasticOut'
    };
    chart.setOption(option);
    return chart;
  })
}

/**
 * 饼状图
 */
function initPie(canvas, width, height, dpr) {
  dpr = getPixelRatio();
  compPie.init((canvas, width, height) =>{
    chartPie = echarts.init(canvas, null, {
      width: width,
      height: height,
      devicePixelRatio: dpr // new
    });
    canvas.setChart(chartPie);

    var option = {
      backgroundColor: "#ffffff",
      color: ["#3399FF", "#0B8887","#FF5755"],
      title:{
        x:'center',
        y:'center',
        top:'140',
        text: '总测试次数',
        textStyle:{
          fontSize: 14,
          color:'#000000',
          fontWeight: 'bold'
        }
      },
      //图形中间文字
      graphic:{
        type:"text",
        left:"center",
        top:"95",
        style:{
            text:"66",
            textAlign:"center",
            fill:"#333333",
            fontSize:40
        }
      },
      series: [{
        hoverAnimation:false,
        itemStyle:{
          borderWidth: 2,
          borderColor: '#FFF'
        },
        label: {
          normal: {
            formatter: ' {b|{b}} {c|{c}次}  \n  {d|{d}%}  \n\n',
            fontSize: 14,
            rich: {
              b: {                        //name 文字样式
                  fontSize: 16,
                  fontWeight:'bold',
                  lineHeight: 25,
                  color: '#333333',
                  align: "center"
              },
              c:{                        //name 文字样式
                fontSize: 16,
                fontWeight:'bold',
                lineHeight: 25,
                color: '#333333',
                align: "center"
            },
              d: {                   //value 文字样式
                  fontSize: 14,
                  fontWeight:'bold',
                  lineHeight: 25,
                  color: '#999999',
                  align: "center"
              }
            }
          }
        },
        type: 'pie',
        center: ['50%', '50%'],
        radius: ['40%', '55%'],
        data: [
          // {
          //   value: 40,
          //   name: '高血糖'
          // }, {
          //   value: 30,
          //   name: '低血糖'
          // }, {
          //   value: 20,
          //   name: '正常'
          // }
        ]
      }]
    };

    chartPie.setOption(option);
    return chartPie;
  })
}

/**
 * 树形图1
 */
function initBar1(canvas, width, height, dpr) {
  dpr = getPixelRatio();
  compTree1.init((canvas, width, height) =>{
    chartTree1 = echarts.init(canvas, null, {
      width: width,
      height: height,
      devicePixelRatio: dpr // new
    });
    canvas.setChart(chartTree1);

    var data = [120, 200, 150, 80, 70, 110, 130];


    var axisCommonX = {
      // 坐标轴字体
      axisLabel: {
        textStyle: {
          color: '#333333',
          fontWeight:'bold',
        }
      },
      // 超出的部分
      axisTick: {
        show:false,
        lineStyle: {
          color: '#708FF9'
        }
      },
      // 最外层坐标轴
      axisLine: {
        lineStyle: {
          type: 'dotted',
          color: '#C8C8C8'
        }
      },
      // 网格线
      splitLine: {
        show:false
      },
      type: 'category',
      data: ['最高值','最低值']
    },
    axisCommonY = {
      // 坐标轴字体
      axisLabel: {
        textStyle: {
          color: '#C8C8C8'
        }
      },
      // 超出的部分
      axisTick: {
        show:false,
        lineStyle: {
          color: '#fff'
        }
      },
      // 最外层坐标轴
      axisLine: {
        show:false,
        lineStyle: {
          color: '#C8C8C8'
        }
      },
      // 网格线
      splitLine: {
        lineStyle: {
          color: '#C8C8C8',
          type: 'dotted'
        }
      },
    };

    var option = {
      grid:{
        top: 35,
        bottom:30,
        right: 10,
        left: 30
      },
      color: ["#FF5755","#3399FF", "#0B8887"],
      backgroundColor: '#FFF',
      xAxis: axisCommonX,
      yAxis: axisCommonY,
      title:{
        x:'center',
        y:'top',
        text: '血糖最值(mmol/L)',
        textStyle:{
          fontSize: 14,
          fontWeight:'bold',
          color:'#333',
        }
      },
      // 数据图形显示
      series: [{
        type: 'bar',
        barWidth: 20,
        data: data,
        itemStyle: {
          normal: {
            color: function(params){
              var color = ["#FF5755","#3399FF", "#0B8887"];
              return color[params.dataIndex]
            },
            label: {
                show: true,		//开启显示
                position: 'top',	//在上方显示
                textStyle: {	    //数值样式
                    color: 'black',
                    fontSize: 10
                }
            }
          }
        }
      }],
      animationDelay: function (idx) {
        return idx * 50;
      },
      animationEasing: 'elasticOut'
    };
    chartTree1.setOption(option);
    return chartTree1;
  })
}

/**
 * 树形图2
 */
function initBar2(canvas, width, height, dpr) {
  dpr = getPixelRatio();
  compTree2.init((canvas, width, height) =>{
    chartTree2 = echarts.init(canvas, null, {
      width: width,
      height: height,
      devicePixelRatio: dpr // new
    });
    canvas.setChart(chartTree2);

    var data = [120, 75, 150, 30];


    var axisCommonX = {
      // 坐标轴字体
      axisLabel: {
        interval:0,
        textStyle: {
          color: '#333333',
          fontWeight:'bold',
        }
      },
      // 超出的部分
      axisTick: {
        show:false,
        lineStyle: {
          color: '#708FF9'
        }
      },
      // 最外层坐标轴
      axisLine: {
        lineStyle: {
          type: 'dotted',
          color: '#C8C8C8'
        }
      },
      // 网格线
      splitLine: {
        show:false
      },
      type: 'category',
      data: ['餐前','餐后','睡前']
    },
    axisCommonY = {
      // 坐标轴字体
      axisLabel: {
        textStyle: {
          color: '#C8C8C8'
        }
      },
      // 超出的部分
      axisTick: {
        show:false,
        lineStyle: {
          color: '#fff'
        }
      },
      // 最外层坐标轴
      axisLine: {
        show:false,
        lineStyle: {
          color: '#C8C8C8'
        }
      },
      // 网格线
      splitLine: {
        lineStyle: {
          color: '#C8C8C8',
          type: 'dotted'
        }
      },
    };

    var option = {
      grid:{
        top: 35,
        bottom:30,
        right: 10,
        left: 30
      },
      color: ["#FF5755","#3399FF", "#0B8887"],
      backgroundColor: '#FFF',
      xAxis: axisCommonX,
      yAxis: axisCommonY,
      title:{
        x:'center',
        y:'top',
        text: '平均值(mmol/L)',
        textStyle:{
          fontSize: 14,
          fontWeight:'bold',
          color:'#333',
        }
      },
      // 数据图形显示
      series: [{
        type: 'bar',
        barWidth: 20,
        data: data,
        itemStyle: {
          normal: {
            color: function(params){
              var color = ["#FF5755","#3399FF", "#0B8887"];
              return color[params.dataIndex]
            },
            label: {
                show: true,		//开启显示
                position: 'top',	//在上方显示
                textStyle: {	    //数值样式
                    color: 'black',
                    fontSize: 10
                }
            }
          }
        }
      }],
      animationDelay: function (idx) {
        return idx * 50;
      },
      animationEasing: 'elasticOut'
    };
    chartTree2.setOption(option);
    return chartTree2;
  })
}